{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37fc971d",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "8aabe9af",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-24T12:45:58.031850Z",
     "start_time": "2022-05-24T12:45:58.027849Z"
    }
   },
   "outputs": [],
   "source": [
    "API_KEY = 'rQBeM08LBtla2sl3DNMRMROa'\n",
    "SECRET_KEY = 'nqRvRezIz5r3AExx4dNKL1sGtXdppH42'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2f80ca9c",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "37188692",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2dae2412",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8f4df9e9",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "8d1b40ca",
   "metadata": {},
   "source": [
    "### 图灵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "9df73203",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-24T12:18:52.363867Z",
     "start_time": "2022-05-24T12:18:52.349866Z"
    }
   },
   "outputs": [],
   "source": [
    "TL_key = \"d5d5bb66f66d4da8bedb378df7adfa70\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "72622c31",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-24T12:23:26.609553Z",
     "start_time": "2022-05-24T12:23:26.605553Z"
    }
   },
   "outputs": [],
   "source": [
    "import requests,json\n",
    "#json.dumps 将python "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "30d0bab0",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-24T12:26:28.440953Z",
     "start_time": "2022-05-24T12:26:28.117934Z"
    }
   },
   "outputs": [],
   "source": [
    "TL_url = 'http://openapi.turingapi.com/openapi/api/v2'\n",
    "\n",
    "parmas  = {\n",
    "  \"reqType\":0,\n",
    "    \"perception\": {\n",
    "        \"inputText\": {\n",
    "            \"text\": \"香蕉用英文怎么说\"\n",
    "        },\n",
    "    },\n",
    "    \"userInfo\": {\n",
    "        \"apiKey\": TL_key,\n",
    "        \"userId\": \"000001\"\n",
    "    }\n",
    "}\n",
    "\n",
    "res = requests.post(url=TL_url,data= json.dumps(parmas))\n",
    "return res.json()['results'][0]['values']['text']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "7354c203",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2022-05-24T12:26:32.011157Z",
     "start_time": "2022-05-24T12:26:32.004157Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'intent': {'actionName': '', 'code': 10020, 'intentName': ''},\n",
       " 'results': [{'groupType': 1,\n",
       "   'resultType': 'text',\n",
       "   'values': {'text': 'banana'}}]}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "res.json()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c2b9692",
   "metadata": {},
   "outputs": [],
   "source": [
    "'''\n",
    "1. 获取token\n",
    "2. asr语音识别技术\n",
    "3. tts语音合成技术\n",
    "\n",
    "'''\n",
    "import sys\n",
    "import json\n",
    "import time\n",
    "\n",
    "from urllib.request import urlopen\n",
    "from urllib.request import Request\n",
    "from urllib.error import URLError\n",
    "from urllib.parse import urlencode\n",
    "from urllib.parse import quote_plus\n",
    "timer = time.perf_counter\n",
    "\n",
    "SCOPE = 'audio_voice_assistant_get' \n",
    "TOKEN_URL = 'http://aip.baidubce.com/oauth/2.0/token'\n",
    "ASR_URL = 'http://vop.baidu.com/server_api'\n",
    "\n",
    "# 1. 获取token\n",
    "def fetch_token(API_KEY,SECRET_KEY):\n",
    "    \n",
    "    params = {\n",
    "        'grant_type': 'client_credentials',\n",
    "        'client_id': API_KEY,\n",
    "        'client_secret': SECRET_KEY\n",
    "    }\n",
    "    post_data = urlencode(params)\n",
    "    post_data = post_data.encode('utf-8')\n",
    "    req = Request(TOKEN_URL, post_data)\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "    except URLError as err:\n",
    "        print('token http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    result_str = result_str.decode()\n",
    "    result = json.loads(result_str)\n",
    "    if ('access_token' in result.keys() and 'scope' in result.keys()):\n",
    "        if SCOPE and (not SCOPE in result['scope'].split(' ')):  # SCOPE = False 忽略检查\n",
    "            raise DemoError('scope is not correct')\n",
    "        return result['access_token']\n",
    "    else:\n",
    "        raise DemoError('MAYBE API_KEY or SECRET_KEY not correct: access_token or scope not found in token response')\n",
    "\n",
    "# 2. 语音识别       \n",
    "def asr(token,AUDIO_FILE,CUID='123456PYTHON',DEV_PID=1537,RATE=16000): \n",
    "    speech_data = []\n",
    "    with open(AUDIO_FILE, 'rb') as speech_file:\n",
    "        speech_data = speech_file.read()\n",
    "    length = len(speech_data)\n",
    "    if length == 0:\n",
    "        raise DemoError('file %s length read 0 bytes' % AUDIO_FILE)\n",
    "    params = {'cuid': CUID, 'token': token, 'dev_pid': DEV_PID}\n",
    "    params_query = urlencode(params);\n",
    "    headers = {\n",
    "        'Content-Type': 'audio/' + AUDIO_FILE[-3:] + '; rate=' + str(RATE),\n",
    "        'Content-Length': length\n",
    "    }\n",
    "    url = ASR_URL + \"?\" + params_query\n",
    "    req = Request(ASR_URL + \"?\" + params_query, speech_data, headers)\n",
    "    try:\n",
    "        begin = timer()\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "        print(\"Request time cost %f\" % (timer() - begin))\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "    result_str = str(result_str, 'utf-8')\n",
    "    with open(\"result.txt\", \"w\") as of:\n",
    "        of.write(result_str)\n",
    "    return result_str\n",
    "\n",
    "\n",
    "# 3. 语音合成\n",
    "\n",
    "TTS_URL = 'http://tsn.baidu.com/text2audio'\n",
    "\n",
    "def tts(token,TEXT,CUID='123456PYTHON'):\n",
    "    # 发音人选择, 基础音库：0为度小美，1为度小宇，3为度逍遥，4为度丫丫，\n",
    "    # 精品音库：5为度小娇，103为度米朵，106为度博文，110为度小童，111为度小萌，默认为度小美 \n",
    "    PER = 4\n",
    "    # 语速，取值0-15，默认为5中语速\n",
    "    SPD = 5\n",
    "    # 音调，取值0-15，默认为5中语调\n",
    "    PIT = 5\n",
    "    # 音量，取值0-9，默认为5中音量\n",
    "    VOL = 5\n",
    "    # 下载的文件格式, 3：mp3(default) 4： pcm-16k 5： pcm-8k 6. wav\n",
    "    AUE = 6\n",
    "    FORMATS = {3: \"mp3\", 4: \"pcm\", 5: \"pcm\", 6: \"wav\"}\n",
    "    FORMAT = FORMATS[AUE]\n",
    "    SCOPE = 'audio_tts_post'  # 有此scope表示有tts能力，没有请在网页里勾选\n",
    "    tex = quote_plus(TEXT)  # 此处TEXT需要两次urlencode\n",
    "    params = {'tok': token, 'tex': tex, 'per': PER, 'spd': SPD, 'pit': PIT, 'vol': VOL, 'aue': AUE, 'cuid': CUID,\n",
    "              'lan': 'zh', 'ctp': 1}  # lan ctp 固定参数\n",
    "\n",
    "    data = urlencode(params)\n",
    "    #     print('test on Web Browser' + TTS_URL + '?' + data)\n",
    "\n",
    "    req = Request(TTS_URL, data.encode('utf-8'))\n",
    "    has_error = False\n",
    "    try:\n",
    "        f = urlopen(req)\n",
    "        result_str = f.read()\n",
    "\n",
    "        headers = dict((name.lower(), value) for name, value in f.headers.items())\n",
    "\n",
    "        has_error = ('content-type' not in headers.keys() or headers['content-type'].find('audio/') < 0)\n",
    "    except  URLError as err:\n",
    "        print('asr http response http code : ' + str(err.code))\n",
    "        result_str = err.read()\n",
    "        has_error = True\n",
    "\n",
    "    save_file = \"error.txt\" if has_error else 'result.' + FORMAT\n",
    "    with open(save_file, 'wb') as of:\n",
    "        of.write(result_str)\n",
    "\n",
    "    if has_error:\n",
    "  \n",
    "        result_str = str(result_str, 'utf-8')\n",
    "        print(\"tts api  error:\" + result_str)\n",
    "\n",
    "    print(\"result saved as :\" + save_file)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.8"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  },
  "varInspector": {
   "cols": {
    "lenName": 16,
    "lenType": 16,
    "lenVar": 40
   },
   "kernels_config": {
    "python": {
     "delete_cmd_postfix": "",
     "delete_cmd_prefix": "del ",
     "library": "var_list.py",
     "varRefreshCmd": "print(var_dic_list())"
    },
    "r": {
     "delete_cmd_postfix": ") ",
     "delete_cmd_prefix": "rm(",
     "library": "var_list.r",
     "varRefreshCmd": "cat(var_dic_list()) "
    }
   },
   "types_to_exclude": [
    "module",
    "function",
    "builtin_function_or_method",
    "instance",
    "_Feature"
   ],
   "window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
